package com.xneure.database;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import com.xneure.database.dao.DataBaseDao;
import com.xneure.database.dao.Paging;
import com.xneure.database.sql.handler.SqlHandler;

public class BaseService<T,D extends DataBaseDao<T>>{
	@Autowired
	D dao;
	Class<T> entityClass;
	private QueryExpression queryExp;

	@SuppressWarnings("unchecked")
	public BaseService(){
		super();
		ParameterizedType type = (ParameterizedType)(getClass()).getGenericSuperclass();
		if(null != type){
			Type[] current = type.getActualTypeArguments();
			if(current[0] instanceof ParameterizedType){
				type = (ParameterizedType)current[0];
				entityClass = (Class<T>)type.getActualTypeArguments()[0];
			}
			entityClass = (Class<T>)current[0];
		}
		initQueryExp();
	}

	protected QueryExpression initQueryExp(){
		return queryExp = new QueryExpression(" select * from " + SqlHandler.getMetaObject(getEntityClass()).getTableName());
	}

	public Class<T> getEntityClass(){
		return entityClass;
	}

	public String compileQuerySql(Map<String,Object> condition){
		for(Entry<String,Object> ent:condition.entrySet()){
			queryExp.resolve(ent.getKey(),ent.getValue());
		}
		String sql = queryExp.toSql();
		queryExp.reset();
		return sql;
	}

	public String getQueryAll(){
		return queryExp.toSql();
	}

	public D getDao(){
		return dao;
	}

	public T query(T entity){
		return dao.query(entity);
	}

	public T queryById(Object id){
		return dao.queryById(getEntityClass(),id);
	}

	public void delete(T entity){
		dao.delete(entity);
	}

	public void insert(T entity){
		dao.insert(entity);
	}

	public void updata(T entity){
		dao.updata(entity);
	}

	public List<T> getList(T entity,Paging page){
		return dao.getList(entity,page);
	}

	public List<T> getListWhere(T entity,String where){
		return dao.getListWhere(entity,where);
	}

	public List<T> getListWhere(String where){
		return dao.getListClassWhere(getEntityClass(),where);
	}

	public T queryWhere(T entity,String where){
		return dao.queryWhere(entity,where);
	}

	public T queryWhere(String Where){
		return dao.queryClassWhere(getEntityClass(),Where);
	}

	public List<T> queryBySql(String sql){
		return dao.queryBySql(getEntityClass(),sql);
	}

	public <O> List<O> queryBySql(Class<O> cls,String sql){
		return dao.queryBySql(cls,sql);
	}

	public T query(String sql){
		return dao.querySql(getEntityClass(),sql);
	}

	public <O> O query(Class<O> cls,String sql){
		return dao.querySql(cls,sql);
	}

	public Object executeSql(String sql){
		return dao.executeSql(sql);
	}
}
